import csv

from util.tools import parse
from util.equation import Equation
from util.exercise import Exercise


# 一维数组变二维数组
def one_d_to_two_d(one_d_array, chunk_size):
    return [one_d_array[i:i + chunk_size] for i in range(0, len(one_d_array), chunk_size)]


def write_exercise_to_file(filename: str, num: int, exercise: Exercise):
    with open(filename, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        # 写入数据
        rs_list = [item.toStringNoAnswer() for item in exercise.equationList]
        data = one_d_to_two_d(rs_list, num)
        writer.writerows(data)


def read_exercise_from_file(fileName):
    with open(fileName, mode='r', encoding='utf-8') as file:
        # 创建CSV阅读器
        reader = csv.reader(file)
        equationList: list[Equation] = []
        answer: list[int] = []
        # 遍历CSV文件中的每一行
        for row in reader:
            for item in row:
                # 解析成算式对象，和答案列表，并存入 ArithmeticPractice 中的 exercise
                equation, rs = parse(item)
                equationList.append(equation)
                answer.append(rs)
        return equationList, answer


# 统计结果
def write_check_to_file(fileName: str, exercise: Exercise):
    with open(fileName, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        data = []
        data.append(["正确", "错误", "总数"])
        total = exercise.rightCount + exercise.wrongCount
        data.append([exercise.rightCount,
                    exercise.wrongCount, total])
        writer.writerows(data)
